package com.xmim.fulcrum.handler.impl;

import com.xmim.core.cocurrent.FutureTaskScheduler;
import com.xmim.core.constants.MessageCode;
import com.xmim.core.entity.Message;
import com.xmim.core.session.user.UserSession;
import com.xmim.fulcrum.FulcrumDiscover;
import com.xmim.fulcrum.session.FulcrumSession;
import com.xmim.fulcrum.handler.AbstractMessageHandler;
import com.xmim.fulcrum.node.FulcrumNode;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HeartbeatHandler extends AbstractMessageHandler<FulcrumNode> {


    public HeartbeatHandler(FulcrumDiscover fulcrumDiscover) {
        super(fulcrumDiscover);
    }

    @Override
    public Integer getType() {
        return MessageCode.MSG_FULCRUM_HEARTBEAT;
    }

    @Override
    public void handler0(UserSession session, Message<FulcrumNode> msg) {
        if (MessageCode.MSG_FULCRUM_HEARTBEAT == msg.getType()) {
            return;
        }
        FulcrumSession sender = senderManager.getSession(String.valueOf(msg.getBody().getId()));
        //异步处理,将心跳包，直接回复给客户端
        FutureTaskScheduler.add(() -> {
            if (session.isValid() && sender.isConnect()) {
                sender.writeAndFlush(msg);
            }
        });
    }

    @Override
    protected Class<?> getMessageClass() {
        return FulcrumNode.class;
    }
}
